import { Menu } from 'antd';
import { v1 as uuid } from 'uuid';
import { Link } from 'react-router-dom';
import { memo } from 'react';
import SubMenu from 'antd/lib/menu/SubMenu';

/**
 * @class 单独的导航栏
 */
export class MenuItem {
  url = '';

  name = '';

  icon?: React.ReactNode;

  constructor(url: string, name: string, icon?: React.ReactNode) {
    this.url = url;
    this.name = name;
    this.icon = icon;
  }
}

/**
 * @class 组导航栏带有标题
 */
export class MenuItemGroup {
  title: string = '';

  children: MenuItem[] = [];

  icon?: React.ReactNode;

  constructor(title: string, children: MenuItem[], icon?: React.ReactNode) {
    this.title = title;
    this.children = children.map(
      (child) => new MenuItem(child.url, child.name, child.icon)
    );
    this.icon = icon;
  }
}
export interface Props {
  menuData: (MenuItem | MenuItemGroup)[];
}

export default memo((props: Props) => {
  const { menuData } = props;

  return (
    <Menu theme="dark" mode="inline">
      {menuData.map((menuDataItem) => {
        if (menuDataItem instanceof MenuItem) {
          return (
            <Menu.Item key={uuid()} icon={menuDataItem.icon}>
              <Link to={menuDataItem.url}>
                <span>{menuDataItem.name}</span>
              </Link>
            </Menu.Item>
          );
        } if (menuDataItem instanceof MenuItemGroup) {
          return (
            <SubMenu
              key={uuid()}
              title={menuDataItem.title}
              icon={menuDataItem.icon}
            >
              {menuDataItem.children.map((menuSubItem) => (
                <Menu.Item key={uuid()} icon={menuDataItem.icon}>
                  <Link to={menuSubItem.url}>
                    <span>{menuSubItem.name}</span>
                  </Link>
                </Menu.Item>
              ))}
            </SubMenu>
          );
        }
        return null;
      })}
    </Menu>
  );
});
